﻿using System;
using System.Collections.Generic;
using System.Web.UI;

namespace WebDiagnostics.Diagnosers.DatabaseConnectivity
{
    public class DatabaseConnectivityDiagnosis : Diagnosis
    {
        public IEnumerable<DatabaseQueryResult> Results { get; set; }

        public DatabaseConnectivityDiagnosis(IEnumerable<DatabaseQueryResult> results)
        {
            Results = results;
        }

        public override void Render(System.IO.TextWriter writer)
        {
            var htmlWriter = new HtmlTextWriter(writer);

            htmlWriter.RenderHeader(2, "Database Connections");

            htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "scrollable");
            htmlWriter.RenderBeginDiv("scrollable");

            htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "database-connections");
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Table);

            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Thead);
            htmlWriter.WriteLine("<tr> <th>Name</th> <th>Status</th> </tr>");
            htmlWriter.RenderEndTag();

            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tbody);
            foreach (var result in Results)
                RenderResult(result, htmlWriter);
            htmlWriter.RenderEndTag();

            htmlWriter.RenderEndTag();
            htmlWriter.RenderEndTag();
        }

        private void RenderResult(DatabaseQueryResult result, HtmlTextWriter htmlWriter)
        {
            string rowClass = "registered-route " + result.Result;

            htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, rowClass);
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tr);

                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td);
                htmlWriter.Write(result.Name);
                htmlWriter.RenderEndTag();

                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Title, result.Message);
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td);
                htmlWriter.Write(result.Result);
                htmlWriter.RenderEndTag();

            htmlWriter.RenderEndTag();
        }
    }
}